<template>
    <el-dialog v-model="drawer" :close-on-click-modal="false" destroy-on-close width="55%" @close="closeMatter" title="报价单">
        <el-form :model="formData" :rules="formRules" ref="formRef" size="small" :inline="false" label-width="100px">
            <el-row style="margin-bottom: 18px">
                <el-col :span="12">
                    <el-form-item label="报价主题" prop="title">
                        <el-input v-model="formData.title" maxlength="64" clearable placeholder="请填写报价主题" />
                    </el-form-item>
                    <el-form-item label="报价金额" prop="amount">
                        <template style="display: flex; flex-direction: row;">
                            <el-input-number v-model="formData.amount" placeholder="请填写报价金额" style="width: 200px"
                                :max="99999999" :min="0" :precision="2" :controls="false" />
                            <el-checkbox style="margin-left: 10px" v-model="formData.amountTax" label="是否含税" :true-label="1"
                                :false-label="0" size="small" />
                        </template>
                    </el-form-item>
                    <el-form-item label="交付说明" prop="submitExplain">
                        <el-input v-model="formData.submitExplain" placeholder="请填写交付说明" clearable />
                    </el-form-item>
                    <el-form-item label="运输说明" prop="transportExplain">
                        <el-input v-model="formData.transportExplain" placeholder="请填写运输说明" clearable />
                    </el-form-item>
                    <el-form-item label="包装说明" prop="packageExplain">
                        <el-input v-model="formData.packageExplain" placeholder="请填写包装说明" clearable />
                    </el-form-item>
                    <el-form-item label="报价日期" prop="quoteDate">
                        <el-date-picker v-model="formData.quoteDate" type="date" placeholder="请选择报价日期" size="small"
                            value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="客户" prop="customerId">
                        <el-select v-model="formData.customerId" placeholder="请选择报价单位" clearable filterable
                            @change="supplierChange">
                            <el-option v-for="item in customerList" :key="item.id" :value="item.id"
                                :label="item.nickname" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="接收人" prop="contactId">
                        <el-select v-model="formData.contactId" :placeholder="formData.customerId ? '请选择接收人' : '请先选择客户'"
                            @change="contactChange" clearable filterable>
                            <el-option v-for="item in contactList" :key="item.id" :value="item.id" :label="item.name" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="结款方式" prop="paymentType">
                        <el-select v-model="formData.paymentType" placeholder="请选择结款方式" clearable filterable>
                            <el-option v-for="item in dictMap['PaymentType']" :key="item.value" :label="item.name"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="报价单位">
                        <el-tag type="success">{{ enterpriseMap.name }}</el-tag>
                    </el-form-item>
                    <el-form-item label="报价人">
                        <el-tag>{{ formData.userName ? formData.userName : '当前操作人' }}</el-tag>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="描述" prop="remark">
                <el-input v-model="formData.remark" type="textarea" :rows="3" />
            </el-form-item>
            <el-divider />
            <el-form-item label="产品清单"></el-form-item>
            <el-table :data="formData.productList" stripe height="240" :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }">
                <el-table-column label="序号" type="index" width="75" />
                <el-table-column label="产品名称" width="150" prop="name">
                    <template v-slot="{ row }">
                        <el-select v-model="row.name" allow-create filterable default-first-option clearable>
                            <el-option v-for="item in productNames" :key="item.id" :value="item.name" :label="item.name" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="型号" width="150" prop="ver">
                    <template v-slot="{ row }">
                        <!-- <el-input v-model="row.ver" maxlength="64" clearable/> -->
                        <span>{{ row.ver }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="详情/规格" width="150" prop="specs">
                    <template v-slot="{ row }">
                        <!-- <el-input v-model="row.spec" maxlength="255" clearable/> -->
                        <span>{{ row.specs }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="数量" width="100" prop="quantity">
                    <template v-slot="{ row }">
                        <el-input-number v-model="row.quantity" :min="0" :max="999999" :controls="false" style="width: 90px"
                            @change="calAmount(row)" />
                    </template>
                </el-table-column>
                <el-table-column label="价格" width="130" prop="price">
                    <template v-slot="{ row }">
                        <!-- <el-input-number v-model="row.price" :min="0" :max="999999" :controls="false" :precision="2" style="width: 120px" @change="calAmount(row)"/> -->
                        <span style="color: red">{{ row.price }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="小计" width="140" prop="total" />
                <el-table-column label="备注" prop="remark">
                    <template v-slot="{ row }">
                        <el-input v-model="row.remark" type="textarea" :rows="2" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="90">
                    <template v-slot="{ $index, row }">
                        <el-button type="danger" :icon="Delete" text @click="removeProduct($index, row)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row style="margin-top: 5px;width: 100%">
                <el-col :span="3" :offset="1">
                    <el-button type="primary" :icon="Plus" @click="addProduct" text>添加</el-button>
                </el-col>
                <el-col :span="5">合计：{{ formData.productAmountSum }} 元</el-col>
                <el-col :span="6">大写：{{ numToChinese(formData.productAmountSum) }}</el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button size="small" @click="closeMatter">关闭</el-button>
            <el-button size="small" type="primary" @click="submitQuotation(formRef, 0)">保存到报价单</el-button>
            <el-button size="small" type="primary" @click="submitQuotation(formRef, 1)">提交并发送</el-button>
        </template>

        <product-list v-model:dialogDrawer="dialogProduct" @onSubmit="submitProduct"></product-list>
    </el-dialog>
</template>
  
<script>
// 报价单
import { computed, reactive, ref, toRefs } from 'vue'
import { getDictByCodes } from '/@/api/sys/dict'
import { numToChinese } from '/@/utils/common'
import { Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import ProductList from '/@/views/order/components/ProductList.vue'
import api from '/@/api/commonApi'

export default {
    name: 'QuotationOrder',
    emits: ['callback', 'update:code'],
    components: {
        ProductList
    },
    props: {
        code: {
            type: String,
            default: ''
        },
        supplierId: {   // 供应商信息id
            type: String,
            default: null
        }
    },
    setup(props, context) {
        const formRef = ref()
        const { code, supplierId } = toRefs(props)
        let drawer = computed({
            get: () => {
                let flag = code.value == state.formData.type
                if (flag) {
                    getDictByCodes(['PaymentType']).then(res => state.dictMap = res.data).catch(e => console.log(e))
                    // 获取客户列表
                    api.customerList().then(res => {
                        state.customerList = res.data
                    })
                    // 获取当前报价单位
                    api.nowEnterpriseInfo().then(res => {
                        state.enterpriseMap = res.data
                    })
                }
                return flag
            },
            set: val => context.emit('update:code', val ? state.formData.type : '')
        })
        const state = reactive({
            formData: {
                title: '',
                type: 'QUOTATION_ORDER',
                userId: '',
                userName: '',
                customerId: '',
                contactId: '',
                amount: 0,
                amountTax: 0,
                paymentType: null,
                submitExplain: '',
                transportExplain: '',
                packageExplain: '',
                primeRate: 0,
                discountAmount: 0,
                quoteDate: '',
                remark: '',
                productList: [],
                matter: 0,   // 是否加到事项, 0否 1是
            },
            formRules: {
                title: { required: true, message: '请填写报价单主题', trigger: 'blur' },
                customerId: { required: true, message: '请选择客户', trigger: 'change' }
            },
            dictMap: {},
            productNames: [],   // 产品名称列表
            customerList: [],   // 客户列表
            contactList: [],  // 客户联系人列表
            enterpriseMap: { // 报价单位
                name: ''
            },
            dialogProduct: false, // 添加商品弹窗
        })

        const resetForm = () => {
            state.tempId = 0
            state.customerUser = { name: '' }
            state.formData = {
                title: '',
                type: 'QUOTATION_ORDER',
                userId: '',
                userName: '',
                customerId: '',
                contactId: '',
                amount: 0,
                amountTax: 0,
                paymentType: null,
                submitExplain: '',
                transportExplain: '',
                packageExplain: '',
                primeRate: 0,
                discountAmount: 0,
                quoteDate: '',
                remark: '',
                productList: [],
                matter: 0   // 是否加到事项, 0否 1是
            }
        }
        const addProduct = () => {
            state.dialogProduct = true
        }
        // 移除产品行
        const removeProduct = (index, product) => {
            state.formData.productItems.splice(index, 1)
            state.formData.productAmountSum -= product.total
        }
        // 客户改动
        const supplierChange = (supplierInfoId) => {
            api.getCustomerContacts({ memberId: supplierInfoId }).then(res => {
                state.formData.contactId = null
                state.formData.userId = null
                state.formData.userName = ''
                state.contactList = res.data
                api.customerUserList({ customerId: supplierInfoId }).then(res => {
                    if (res.data.length > 0) {
                        state.formData.userId = res.data[0].userId
                        state.formData.userName = res.data[0].userName
                    }
                })
            })
            let cusromer = state.customerList.find(e => {
                return e.id == supplierInfoId
            })
            if (cusromer.sysUserId) {
                api.customerSuppliers({
                    userId: cusromer.sysUserId
                }).then(res => {
                    if(res.data.length == 0) {
                        ElMessage.warning("未被该客户添加为供应商")
                    }
                })
            }else{
                ElMessage.warning("未被该客户添加为供应商")
            }
        }
        // 联系人改动
        const contactChange = (contactId) => {
            for (let i = 0; i < state.contactList.length; i++) {
                let item = state.contactList[i]
                if (item.id == contactId) {
                    state.formData.contactPhone = item.phone
                    break
                }
            }
        }
        // 产品合计
        const calAmount = (product) => {
            let total = 0
            product.total = ((product.quantity || 0) * (product.price || 0)).toFixed(2)
            state.formData.productList.forEach(item => total += (item.quantity || 0) * (item.price || 0))
            state.formData.productAmountSum = total.toFixed(2)
        }
        const submitQuotation = (formRef, type) => {
            state.formData.matter = type
            formRef.validate(async (valid) => {
                if (!valid) {
                    return false
                }
                if (state.formData.productList.length > 0) {
                    if (state.formData.id) {
                        api.editOrderQuote(state.formData).then(res => {
                            ElMessage.success('保存成功！')
                            closeMatter()
                        })
                    } else {
                        api.addOrderQuote(state.formData).then(res => {
                            ElMessage.success('提交成功！')
                            closeMatter()
                        })
                    }
                }else {
                    ElMessage.warning("请添加商品")
                }
            })
        }
        const closeMatter = () => {
            resetForm()
            context.emit('update:code', '')
            context.emit('callback', '')
        }
        // 获取选择的产品
        const submitProduct = val => {
            let list = []
            val.forEach(e => {
                let isExist = state.formData.productList.find(item => {
                    return item.productId == e.chooseSpec[0]
                })
                if (!isExist) {
                    let selSku = e.skuInfos.find(item => {
                        return item.skuId == e.chooseSpec[0]
                    })
                    list.push({
                        id: null,
                        productId: selSku.skuId,
                        name: e.spuName,
                        ver: selSku.skuName,
                        specs: selSku.skuName,
                        quantity: 0,
                        price: selSku.price,
                        total: 0.00,
                        remark: null
                    })
                }
            })
            state.formData.productList = state.formData.productList.concat(list)
        }

        return {
            Plus,
            Delete,
            drawer,
            formRef,
            ...toRefs(state),
            resetForm,
            calAmount,
            addProduct,
            closeMatter,
            numToChinese,
            contactChange,
            removeProduct,
            supplierChange,
            submitQuotation,
            submitProduct
        }
    }
}
</script>
  
<style scoped lang="scss"></style>
  